<?php
/**
 * Created by PhpStorm.
 * User: dt
 * Time: 16:33
 */
namespace  backend\models;

use OSS\Core\OssException;
use OSS\OssClient;
use Yii;


/**
 * Oss操作
 * @package app\models
 */
class OssModel extends \yii\db\ActiveRecord
{
    public $ossClient;
    public $bucket;
    public function init()
    {
        require_once dirname(dirname(__DIR__)) . '/backend/utils/aliyun-oss-php-sdk-2.2.4/autoload.php';
        $accessKeyId = Yii::$app->params['oss']['key'];
        $accessKeySecret = Yii::$app->params['oss']['secret'];
        $endpoint = 'oss-cn-hangzhou.aliyuncs.com';
        $this->bucket = Yii::$app->params['oss']['bucket'];
        try {
            $this->ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
        } catch (\OSS\Core\OssException $e) {

        }
    }

    /**
     * 上传远程图片到oss
     * @param $icon_url
     * @return string
     */
    public function upload_remote_img($icon_url){
        $rs=file_get_contents($icon_url);
        if(strlen($rs) > 100){
            $filename = 'upload/'.date('Ymd',time()).uniqid().'.jpg';
            $res = $this->ossClient->putObject($this->bucket, $filename , $rs);
            if(isset($res['info']['url'])){
                return $filename;
            }
        }
        return '';
    }

    /**
     * 删除图片
     * @param array $list
     * @return bool
     */
    public function dele($list = array())
    {
        try{
            if(empty($list)){
                return true;
            }
            //$this->ossClient->deleteObjects($this->bucket,$list);
            $data = [];
            $date = date('Y-m-d');
            foreach($list as $val){
                $data[]=[$val,$date];
            }
            //需要删除的图片,放删除图片表中
            Yii::$app->db->createCommand()->batchInsert('delete_storage',['resource','create_date'],$data)->execute();
            return true;
        } catch(OssException $e) {
            //printf($e->getMessage() . "\n");
            return false;
        }
    }

    /**
     * 删除旧图片
     * @param $oss
     */
    public function deleOldImage($oss)
    {
        //只获取昨天00:00:00至昨天23:59:59时间段的差异
        $time = strtotime(date('Y-m-d'))-86400;
        $date = date('Ymd',$time);
        //获取昨天所有上传的图片
        $oss_list = $oss->getList($date);
        //获取昨天所有表的图片
        $table_list = $oss->getAllTableImage($date);
        $diff_list = array_diff($oss_list, $table_list);
        if($diff_list){
            $data = [];
            $date = date('Y-m-d',$time);
            foreach($diff_list as $k=>$v){
                $data[intval($k/100)][] = [$v,$date];
            }
            foreach($data as $val){
                //需要删除的图片,放删除图片表中
                Yii::$app->db->createCommand()->batchInsert('delete_storage',['resource','create_date'],$val)->execute();
            }
        }
    }

    /**
     * 获取所有表图片字段
     * @param $date
     * @return array
     */
    public function getAllTableImage($date)
    {
        $start_time = strtotime($date);
        $end_time = $start_time+86399;
        $condition = '(create_time between '.$start_time.' and '. $end_time.') or (update_time between '.$start_time.' and '. $end_time.')';
        $list1 = UserModel::find()->select('icon')->where($condition)->asArray()->column();
        $list2 = CourseModel::find()->select('image')->where($condition)->asArray()->column();
        $list3 = CourseVideoModel::find()->select('image')->where($condition)->asArray()->column();
        $list4 = SlidersImageModel::find()->select('image')->where($condition)->asArray()->column();
        return array_merge($list1,$list2,$list3,$list4);
    }

    /**
     * 获取全部列表文件名
     * @return array|void
     */
    public function getList($prefix='')
    {
        if($prefix == ''){
            return [];
        }
        $list = [];
        $maxkeys = 2;
        $nextMarker = '';
        while(true){
            $options = array(
                'delimiter' => '',
                'prefix' => $prefix,
                'max-keys' => $maxkeys,
                'marker' => $nextMarker,
            );
            try {
                $listObjectInfo = $this->ossClient->listObjects($this->bucket, $options);
            } catch (OssException $e) {
                //printf($e->getMessage() . "\n");
                return;
            }
            $nextMarker = $listObjectInfo->getNextMarker();
            $listObject = $listObjectInfo->getObjectList();
            //$listPrefix = $listObjectInfo->getPrefixList();
            if(!empty($listObject)){
                foreach($listObject as $item){
                    if($item->getKey()){
                        $list[] = $item->getKey();
                    }
                }
            }
            if ($nextMarker === '') {
                break;
            }
        }
        return $list;
    }



    /**
     * 获取Web端直传Oss参数
     * @param string $dir
     * @return string
     */
    public static function getOssUpload($dir='upload',$str=''){
        function gmt_iso8601($time) {
            $dtStr = date("c", $time);
            $mydatetime = new \DateTime($dtStr);
            $expiration = $mydatetime->format(\DateTime::ISO8601);
            $expiration = substr($expiration, 0, strpos($expiration, '+'));
            return $expiration."Z";
        }
        $end = time()+30;
        $expiration = gmt_iso8601($end);//设置该policy超时时间是10s. 即这个policy过了这个有效时间，将不能访问

        //最大文件大小.用户可以自己设置
        $conditions[] = array(0=>'content-length-range', 1=>0, 2=>1048576000);
        //表示用户上传的数据,必须是以$dir开始, 不然上传会失败,这一步不是必须项,只是为了安全起见,防止用户通过policy上传到别人的目录
        $conditions[] = array(0=>'starts-with', 1=>'$key', 2=>'');

        $base64_policy = base64_encode(json_encode(array('expiration'=>$expiration,'conditions'=>$conditions)));
        $signature = base64_encode(hash_hmac('sha1', $base64_policy, Yii::$app->params['oss']['secret'], true));

        $response = array();
        $response['accessid'] = Yii::$app->params['oss']['key'];
        $response['host'] = Yii::$app->params['oss']['host'];
        $response['policy'] = $base64_policy;
        $response['signature'] = $signature;
        $response['expire'] = $end;
        //这个参数是设置用户上传指定的前缀
        if($str=''){
            $str = date('Ymd');
        }
        $response['dir'] = $dir.'/'.$str;
        return json_encode($response);
    }

}
